package org.example.leetcode.core.utils;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.example.leetcode.common.utils.UserInfo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Date;


@Component
public class MyBatisPlusConfig {
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        // 新增和修改时自动填充时间戳
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                //取登录用户信息
                metaObject.setValue("creator", UserInfo.getUserInfo()==null?"System":UserInfo.getUserInfo().getPhone());
//                strictInsertFill(metaObject, "isDeleted", String.class, "N");
                metaObject.setValue("isDeleted", "N");
                metaObject.setValue("createTime", new Date());
                metaObject.setValue("updateTime", new Date());
                metaObject.setValue("modifier",
                        metaObject.getValue("creator"));
            }
            @Override
            public void updateFill(MetaObject metaObject) {
                metaObject.setValue("updateTime", new Date());
                //取登录用户信息
                metaObject.setValue("modifier",UserInfo.getUserInfo()==null?"System":UserInfo.getUserInfo().getPhone());
            }
        };
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

//    @Bean
//    public IdentifierGenerator identifierGenerator() {
//        // 自动生成主键 https://mybatis.plus/guide/id-generator.html
//        return entity -> SnowFlakeUtil.getId();
//    }
}
